package scau.zhong.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import scau.zhong.filter.JwtTokenFilter;
import scau.zhong.filter.JwtVerifyFilter;
import scau.zhong.service.Impl.UserService;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Autowired
    private RsaKeyProperties prop;

    @Bean
    public BCryptPasswordEncoder getEncoder(){
        return new BCryptPasswordEncoder();
    }

    //重写父类方法，指定认证来源为数据库，父类默认内存生成
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(getEncoder());
    }

    //spring security配置信息
    public void configure(HttpSecurity http) throws Exception {
        //System.out.println("初始化spring security配置信息");
        http.csrf()
                .disable()
                .authorizeRequests()
                .antMatchers().permitAll()
                .antMatchers("/login").permitAll()
                //.antMatchers("/user").hasAnyRole("USER")
                //.anyRequest().authenticated()
                .and()
                .addFilter(new JwtTokenFilter(super.authenticationManager(),prop))
                .addFilter(new JwtVerifyFilter(super.authenticationManager(),prop))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);//禁用SESSION

    }

}
